import 'package:dart_iztro/dart_iztro.dart';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:intl/intl.dart';
import 'package:logger/logger.dart';
import 'package:lunar/lunar.dart';

class DateQueryScreen extends StatefulWidget {
  const DateQueryScreen({Key? key}) : super(key: key);

  @override
  State<DateQueryScreen> createState() => _DateQueryScreenState();
}

class _DateQueryScreenState extends State<DateQueryScreen> {
  // 创建实例
  final _dartIztroPlugin = DartIztro();
  Map<String, dynamic>? _baziResult = {};
  Map<String, dynamic>? _chartResult;
  DateTime _selectedDate = DateTime.now();
  String _selectedGender = '男';
  late FixedExtentScrollController _yearController;
  late FixedExtentScrollController _monthController;
  late FixedExtentScrollController _dayController;
  late FixedExtentScrollController _hourController;
  late FixedExtentScrollController _minuteController;

  // 添加状态变量来跟踪选中的值
  int _selectedYear = 0;
  int _selectedMonth = 0;
  int _selectedDay = 0;
  int _selectedHour = 0;
  int _selectedMinute = 0;

  // 生成年份列表（1900-2100）
  List<int> get years => List.generate(201, (index) => 1900 + index);

  // 生成月份列表（1-12）
  List<int> get months => List.generate(12, (index) => index + 1);

  // 根据年月获取天数
  List<int> getDays(int year, int month) {
    return List.generate(
        DateTime(year, month + 1, 0).day, (index) => index + 1);
  }

  // 生成小时列表（0-23）
  List<int> get hours => List.generate(24, (index) => index);

  // 生成分钟列表（0-59）
  List<int> get minutes => List.generate(60, (index) => index);

  // 生成秒数列表（0-59）
  List<int> get seconds => List.generate(60, (index) => index);

  @override
  void initState() {
    super.initState();
    _selectedYear = _selectedDate.year - 1900;
    _selectedMonth = _selectedDate.month - 1;
    _selectedDay = _selectedDate.day - 1;
    _selectedHour = _selectedDate.hour;
    _selectedMinute = _selectedDate.minute;
    _initializeControllers();
  }

  void _initializeControllers() {
    _yearController = FixedExtentScrollController(
      initialItem: _selectedYear,
    );
    _monthController = FixedExtentScrollController(
      initialItem: _selectedMonth,
    );
    _dayController = FixedExtentScrollController(
      initialItem: _selectedDay,
    );
    _hourController = FixedExtentScrollController(
      initialItem: _selectedHour,
    );
    _minuteController = FixedExtentScrollController(
      initialItem: _selectedMinute,
    );
  }

  @override
  void dispose() {
    _yearController.dispose();
    _monthController.dispose();
    _dayController.dispose();
    _hourController.dispose();
    _minuteController.dispose();
    super.dispose();
  }

  void _showDateTimePicker() {
    // 重新初始化滚动控制器 FixedExtentScrollController 在创建时，会依据 initialItem 参数来设定滚动视图的初始位置。
    // 一旦初始化完成，这个初始位置就被固定下来了。也就是说，FixedExtentScrollController 在初始化时记住了起始的滚动位置，
    // 后续若不重新初始化，它不会自动更新到新的位置。
    _initializeControllers();
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return StatefulBuilder(
          builder: (BuildContext context, StateSetter setModalState) {
            return SizedBox(
              height: 300,
              child: Column(
                children: [
                  Container(
                    padding:
                        const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
                    decoration: BoxDecoration(
                      color: Theme.of(context).primaryColor,
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        TextButton(
                          onPressed: () => Navigator.pop(context),
                          child: const Text('取消',
                              style: TextStyle(color: Colors.white)),
                        ),
                        TextButton(
                          onPressed: () {
                            setState(() {
                              _selectedDate = DateTime(
                                years[_selectedYear],
                                months[_selectedMonth],
                                getDays(years[_selectedYear],
                                    months[_selectedMonth])[_selectedDay],
                                hours[_selectedHour],
                                minutes[_selectedMinute],
                              );
                              _calculateBaZi();
                              // _calculateChart();
                            });
                            Navigator.pop(context);
                          },
                          child: const Text('确定',
                              style: TextStyle(color: Colors.white)),
                        ),
                      ],
                    ),
                  ),
                  Expanded(
                    child: Row(
                      children: [
                        Expanded(
                          child: CupertinoPicker(
                            scrollController: _yearController,
                            itemExtent: 32,
                            onSelectedItemChanged: (index) {
                              setModalState(() {
                                _selectedYear = index;
                              });
                            },
                            children: years
                                .map((year) => Center(
                                      child: Text('$year'),
                                    ))
                                .toList(),
                          ),
                        ),
                        Expanded(
                          child: CupertinoPicker(
                            scrollController: _monthController,
                            itemExtent: 32,
                            onSelectedItemChanged: (index) {
                              setModalState(() {
                                _selectedMonth = index;
                              });
                            },
                            children: months
                                .map((month) => Center(
                                      child: Text('$month月'),
                                    ))
                                .toList(),
                          ),
                        ),
                        Expanded(
                          child: CupertinoPicker(
                            scrollController: _dayController,
                            itemExtent: 32,
                            onSelectedItemChanged: (index) {
                              setModalState(() {
                                _selectedDay = index;
                              });
                            },
                            children: getDays(
                              years[_selectedYear],
                              months[_selectedMonth],
                            )
                                .map((day) => Center(
                                      child: Text('$day日'),
                                    ))
                                .toList(),
                          ),
                        ),
                        Expanded(
                          child: CupertinoPicker(
                            scrollController: _hourController,
                            itemExtent: 32,
                            onSelectedItemChanged: (index) {
                              setModalState(() {
                                _selectedHour = index;
                              });
                            },
                            children: hours
                                .map((hour) => Center(
                                      child: Text('$hour时'),
                                    ))
                                .toList(),
                          ),
                        ),
                        Expanded(
                          child: CupertinoPicker(
                            scrollController: _minuteController,
                            itemExtent: 32,
                            onSelectedItemChanged: (index) {
                              setModalState(() {
                                _selectedMinute = index;
                              });
                            },
                            children: minutes
                                .map((minute) => Center(
                                      child: Text('$minute分'),
                                    ))
                                .toList(),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            );
          },
        );
      },
    );
  }

  // 计算星座
  String getZodiac(DateTime date) {
    final month = date.month;
    final day = date.day;
    if ((month == 1 && day >= 20) || (month == 2 && day <= 18)) return "水瓶座";
    if ((month == 2 && day >= 19) || (month == 3 && day <= 20)) return "双鱼座";
    if ((month == 3 && day >= 21) || (month == 4 && day <= 19)) return "白羊座";
    if ((month == 4 && day >= 20) || (month == 5 && day <= 20)) return "金牛座";
    if ((month == 5 && day >= 21) || (month == 6 && day <= 21)) return "双子座";
    if ((month == 6 && day >= 22) || (month == 7 && day <= 22)) return "巨蟹座";
    if ((month == 7 && day >= 23) || (month == 8 && day <= 22)) return "狮子座";
    if ((month == 8 && day >= 23) || (month == 9 && day <= 22)) return "处女座";
    if ((month == 9 && day >= 23) || (month == 10 && day <= 23)) return "天秤座";
    if ((month == 10 && day >= 24) || (month == 11 && day <= 22)) return "天蝎座";
    if ((month == 11 && day >= 23) || (month == 12 && day <= 21)) return "射手座";
    return "摩羯座";
  }

  // 获取农历、生肖、干支年
  Map<String, String> getLunarInfo(DateTime date) {
    final lunar = Lunar.fromDate(date);
    return {
      'lunar':
          "${lunar.getYearInChinese()}年${lunar.getMonthInChinese()}月${lunar.getDayInChinese()}",
      'zodiac': "${lunar.getYearZhi()}年", // 地支年
      'ganZhi': lunar.getYearInGanZhi(), // 干支年，如"庚午"
      'animal': lunar.getYearShengXiao(), // 生肖
    };
  }

  @override
  Widget build(BuildContext context) {
    final lunarInfo = getLunarInfo(_selectedDate);

    return Scaffold(
      appBar: AppBar(
        title: const Text('日期查询'),
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Row(children: [
              const SizedBox(
                  width: 75,
                  child: Text('日期：', style: TextStyle(fontSize: 18))),
              ElevatedButton(
                onPressed: _showDateTimePicker,
                child: Text(
                    DateFormat('yyyy-MM-dd HH:mm:ss').format(_selectedDate)),
              ),
            ]),
            const SizedBox(height: 16),
            Row(
              children: [
                const SizedBox(
                  width: 75,
                  child: Text(
                    '性别：',
                    style: TextStyle(fontSize: 18),
                  ),
                ),
                Row(
                  mainAxisSize: MainAxisSize.min, // 防止 Row 占据全部空间
                  children: [
                    Radio<String>(
                      value: '男',
                      groupValue: _selectedGender,
                      onChanged: (value) {
                        setState(() {
                          _selectedGender = value!;
                        });
                      },
                    ),
                    const Text('男'),
                  ],
                ),
                const SizedBox(width: 16),
                Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Radio<String>(
                      value: '女',
                      groupValue: _selectedGender,
                      onChanged: (value) {
                        setState(() {
                          _selectedGender = value!;
                        });
                      },
                    ),
                    const Text('女'),
                  ],
                ),
              ],
            ),
            const SizedBox(height: 16),
            Row(
              children: [
                const SizedBox(
                    width: 75,
                    child: Text('星座：', style: TextStyle(fontSize: 18))),
                Text(getZodiac(_selectedDate),
                    style: const TextStyle(
                        fontSize: 18, fontWeight: FontWeight.bold)),
              ],
            ),
            const SizedBox(height: 16),
            Row(
              children: [
                const SizedBox(
                    width: 75,
                    child: Text('农历：', style: TextStyle(fontSize: 18))),
                Text(lunarInfo['lunar']!,
                    style: const TextStyle(
                        fontSize: 18, fontWeight: FontWeight.bold)),
              ],
            ),
            const SizedBox(height: 16),
            Row(
              children: [
                const SizedBox(
                    width: 75,
                    child: Text('干支年：', style: TextStyle(fontSize: 18))),
                Text("${lunarInfo['ganZhi']!}年",
                    style: const TextStyle(
                        fontSize: 18, fontWeight: FontWeight.bold)),
              ],
            ),
            const SizedBox(height: 16),
            Row(
              children: [
                const SizedBox(
                    width: 75,
                    child: Text('生肖：', style: TextStyle(fontSize: 18))),
                Text(lunarInfo['animal']!,
                    style: const TextStyle(
                        fontSize: 18, fontWeight: FontWeight.bold)),
              ],
            ),
            const SizedBox(height: 16),
            // 八字结果
            if (_baziResult != null && _baziResult!.isNotEmpty)
              Card(
                child: Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Text(
                    parseString(),
                    style: const TextStyle(fontFamily: 'monospace'),
                  ),
                ),
              ),
            const SizedBox(height: 16),
            if (_chartResult != null)
              Text(
                '紫微斗数：$_chartResult',
                style: const TextStyle(fontSize: 18),
              )
          ],
        ),
      ),
    );
  }

  // 计算八字
  Future<void> _calculateBaZi() async {
    try {
      final result = await _dartIztroPlugin.calculateBaZi(
        year: _selectedDate.year,
        month: _selectedDate.month,
        day: _selectedDate.day,
        hour: _selectedDate.hour,
        minute: _selectedDate.minute,
        isLunar: false,
        gender: _selectedGender,
      );

      setState(() {
        _baziResult = result;
        Logger().d('计算八字结果: $result ${result['yearly']}');
      });
    } catch (e) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('计算出错: ${e.toString()}')));
    }
  }

  // 计算紫微星盘
  _calculateChart() async {
    final chart = await _dartIztroPlugin.calculateChart(
      year: _selectedDate.year,
      month: _selectedDate.month,
      day: _selectedDate.day,
      hour: _selectedDate.hour,
      minute: _selectedDate.minute,
      isLunar: false,
      isLeap: true,
      // 如果是农历，是否调整闰月（默认为true）
      gender: _selectedGender == '男' ? 'male' : 'female',
    );
    setState(() {
      _chartResult = chart;
    });
  }

  String parseString() {
    if (_baziResult == null || _baziResult!.isEmpty) {
      return '';
    }
    final baziString = '''
年柱：${_baziResult!['yearly'][0]}${_baziResult!['yearly'][1]}
月柱：${_baziResult!['monthly'][0]}${_baziResult!['monthly'][1]}
日柱：${_baziResult!['daily'][0]}${_baziResult!['daily'][1]}
时柱：${_baziResult!['hourly'][0]}${_baziResult!['hourly'][1]}''';
    return baziString;
  }
}
